package com.xayy.mgt.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.kawins.base.result.CheckResult;
import cn.kawins.base.utils.CollUtil;
import cn.kawins.mybatis.base.BaseServiceImpl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import com.xayy.core.constant.ConfigCalPath;
import com.xayy.mgt.mapper.HistoryFaultMapper;
import com.xayy.mgt.model.HistoryFault;
import com.xayy.mgt.model.NodeTreeInfo;
import com.xayy.mgt.model.vo.HistoryFaultPageVo;
import com.xayy.mgt.model.xinwangmodel.HistoryFaultMoniVo;
import com.xayy.mgt.service.HistoryFaultService;
import com.xayy.mgt.service.NodeInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class HistoryFaultServiceImpl extends BaseServiceImpl<HistoryFault> implements HistoryFaultService {

    @Resource
    private HistoryFaultMapper historyFaultMapper;

    @Resource
    private NodeInfoService nodeInfoService;

    @Autowired
    private ConfigCalPath configCalPath;

    @Override
    public PageInfo<HistoryFault> pageList(HistoryFaultPageVo nodeInfoDto) {
        if (nodeInfoDto.getPage() == null || nodeInfoDto.getSize() == null) {
            Example example = new Example(HistoryFault.class);
            example.createCriteria().andEqualTo("nodeId", nodeInfoDto.getParentId());
            List<HistoryFault> historyFaultList = historyFaultMapper.selectByExample(example);
            return new PageInfo<>(historyFaultList);
        }
        PageMethod.startPage(nodeInfoDto.getPage(), nodeInfoDto.getSize());
        List<HistoryFault> historyFaultList = historyFaultMapper.pageList(nodeInfoDto);
        return new PageInfo<>(historyFaultList);
    }


    @Override
    public CheckResult<Object> saveHistoryFault(HistoryFault historyFault) {
        CheckResult<?> checkName = checkName(historyFault);
        if (checkName.no()) {
            return CheckResult.fail(checkName.getCheckMsg());
        }
        historyFaultMapper.insert(historyFault);
        return CheckResult.success("新增成功");
    }

    @Override
    public CheckResult<Object> editHistoryFault(HistoryFault historyFault) {
        NodeTreeInfo nodeName = nodeInfoService.selectOne(NodeTreeInfo.builder()
                .satelliteId(historyFault.getSatelliteId()).nodeName(historyFault.getComponents()).build());
        historyFault.setNodeId(nodeName.getId());
        historyFaultMapper.updateByPrimaryKey(historyFault);
        return CheckResult.success("编辑成功");
    }

    @Override
    public CheckResult<Object> deleteHistoryFault(Long id) {
        historyFaultMapper.deleteByPrimaryKey(id);
        return CheckResult.success("删除成功");
    }

    @Override
    public CheckResult<Object> selectOneHistoryFaultDetail(Long id) {
        return CheckResult.success(selectOne(HistoryFault.builder().id(id).build()));
    }

    @Override
    public CheckResult<Object> dataSynchronous(Long nodeId) {
        NodeTreeInfo nodeTreeInfo = nodeInfoService.selectById(nodeId);
        if(nodeTreeInfo == null){
            return CheckResult.success("暂无该节点");
        }
        if(nodeTreeInfo.getLevel() != 0){
            return CheckResult.success("该节点不是卫星节点不可同步");
        }
        HttpResponse execute = HttpRequest.get(configCalPath.getTelAndFaultUrl()+ "/health-xw-back-moni/v1.0/imitate/getHistoryFault?satelliteCode="+nodeTreeInfo.getNodeCode()).execute();
        JSONObject jsonObject = JSONObject.parseObject(execute.body());
        if("200".equals(jsonObject.getString("code"))){
            String data = jsonObject.getString("data");
            List<HistoryFaultMoniVo> historyFaultMoniVos = JSONArray.parseArray(data, HistoryFaultMoniVo.class);
            List<HistoryFault> list = new ArrayList<>();
            historyFaultMoniVos.forEach(item ->{
                HistoryFault historyFault = HistoryFault.builder()
                        .nodeId(nodeId)
                        .satelliteId(nodeTreeInfo.getSatelliteId())
                        .exceptionTime(item.getExceptionTime())
                        .exceptionName(item.getExceptionName())
                        .components(item.getComponents())
                        .persistenceTime(item.getPersistenceTime())
                        .satelliteName(nodeTreeInfo.getNodeName())
                        .seriousDegree(item.getSeriousDegree())
                        .createdTime(new Date())
                        .synchronousTime(new Date())
                        .build();
                list.add(historyFault);
            });
            if(CollUtil.isNotEmpty(list)){
                historyFaultMapper.delete(HistoryFault.builder().nodeId(nodeId).build());
                historyFaultMapper.insertList(list);
            }
            return CheckResult.success("同步成功，本次同步数据“"+list.size()+"”条");
        }
        return CheckResult.fail("同步失败");
    }

    public CheckResult<?> checkName(HistoryFault historyFault) {
        Example example = new Example(HistoryFault.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("satelliteId", historyFault.getSatelliteId());
        criteria.andEqualTo("exceptionName", historyFault.getExceptionName());
        int i = historyFaultMapper.selectCountByExample(example);
        if (i > 0) {
            return CheckResult.fail(historyFault.getExceptionName() + "名称已存在");
        }
        return CheckResult.success();
    }
}
